package com.xpgk.mvc.bentryRegister;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.baseInfoSet.BaseInfoSet;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.intoPersonnel.IntoPersonnel;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productPrice.ProductPrice;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.tools.ToolSqlXml;

import net.sf.json.JSONObject;

public class BentryRegisterController extends BaseController {

	private BentryRegisterService bentryRegisterService = new BentryRegisterService();

	// http://127.0.0.1:8080/shouba2.0/bentryRegister?cusIds=4079464587104234a8fd8a4f5a399fd2
	public void index() {
		String cusIds = getPara("cusIds");
		if (cusIds != null) {
			Customer cus = Customer.dao.findById(cusIds);
			setAttr("customer", cus);
			CustomerAgreement cusagr = cus.getCustomerAgreement();
			Product p = Product.dao.findById(cusagr.getStr(CustomerAgreement.column_codeIds));
			if (p != null && p.getStr(Product.column_proUnits).equals(Code.dlc_units)) {
				setAttr("isdlc", "1");
			}
		}

		List<Record> find = Db
				.find("SELECT ids,`name` from sb_product WHERE typeIds='455018290a8f4afbbaf29c61904d6406'");
		setAttr("product", find);
		setAttr("organids", getCUserOrganIds());
		render("bentryRegister.html");
		
	}
	
	public void getCus() {
		String cusIds = getPara("cusIds");
		if (cusIds != null) {
			Customer cus = Customer.dao.findById(cusIds);
			setAttr("customer", cus);
			CustomerAgreement cusagr = cus.getCustomerAgreement();
			Product p = Product.dao.findById(cusagr.getStr(CustomerAgreement.column_codeIds));
			if (p != null && p.getStr(Product.column_proUnits).equals(Code.dlc_units)) {
				setAttr("isdlc", "1");
			}
		}

		List<Record> find = Db
				.find("SELECT ids,`name` from sb_product WHERE typeIds='455018290a8f4afbbaf29c61904d6406'");
		setAttr("product", find);
		setAttr("organids", getCUserOrganIds());
		render("bentryRegister.html");
	}

	/**
	 * 获取疗程
	 * 
	 */
	public void getLc() {
		String sql = getSqlMy(Product.sqlId_getProductsByType);
		List<Product> pList = Product.dao.find(sql, Code.lc_ids);
		renderJson(pList);
	}
	
	/**
	 * 获取疗程
	 * 
	 */
	public void updateTreatment() {
		String cusIds = getPara("customerIds");
		String codeIds = getPara("customerAgreement.codeIds");//疗程id
		Integer treatment = Integer.parseInt(getPara("customerAgreement.treatment")) ;//疗程数
		String priceIds = Organization.dao.findById(getCUserOrganIds()).getStr(Organization.column_priceIds);
		List<CustomerAgreement> cas = CustomerAgreement.dao.find("SELECT * from sb_customer_agreement WHERE customerIds=? order by createDate desc",cusIds);
		String sql = "select * FROM sb_product_price where priceIds = ? and productIds = ? and status = '1'";
		CustomerAgreement ca= cas.get(0);
		String sqlDel = "SELECT * from sb_customer_detail where customerIds = ? and dataStatus in (1,2)";
		CustomerDetail customerDetail = CustomerDetail.dao.findFirst(sqlDel,cusIds);
		ca.set(CustomerAgreement.column_codeIds, codeIds);
		float cost = 0f;
		if(codeIds.equals("27aeb2d41d044394b9b58f6814baa4fa")){//一
			 cost = ProductPrice.dao.findFirst(sql,priceIds,"27aeb2d41d044394b9b58f6814baa4fa").getFloat(ProductPrice.column_outPrice);
			ca.set(CustomerAgreement.column_cost, cost);
			ca.set(CustomerAgreement.column_treatment, 1);
			customerDetail.set(CustomerDetail.column_sjtreatment, 1)
			.set(CustomerDetail.column_treatmentName, "27aeb2d41d044394b9b58f6814baa4fa");
		}else if(codeIds.equals("0896ce4d4970455d9184e6dd1ced6a0e")){//标准
			cost = ProductPrice.dao.findFirst(sql,priceIds,"0896ce4d4970455d9184e6dd1ced6a0e").getFloat(ProductPrice.column_outPrice);
			ca.set(CustomerAgreement.column_cost, cost*treatment);
			ca.set(CustomerAgreement.column_treatment, treatment);
			customerDetail.set(CustomerDetail.column_sjtreatment, treatment)
			.set(CustomerDetail.column_treatmentName, "0896ce4d4970455d9184e6dd1ced6a0e");
		}else if(codeIds.equals("4777c2c215b6408ab13c1eac4190ce46")){//单
			cost = ProductPrice.dao.findFirst(sql,priceIds,"4777c2c215b6408ab13c1eac4190ce46").getFloat(ProductPrice.column_outPrice);
			ca.set(CustomerAgreement.column_cost, cost);
			ca.set(CustomerAgreement.column_treatment, 1);
			customerDetail.set(CustomerDetail.column_sjtreatment, 1)
			.set(CustomerDetail.column_treatmentName, "4777c2c215b6408ab13c1eac4190ce46");
		}
		ca.update();
		customerDetail.update();
		renderJson( cost*treatment);
	}

	
	
	/**
	 * 获取一疗程
	 * 
	 */
	public void getYlc() {
		String sql = getSqlMy(Product.sqlId_ylc);
		Product p = Product.dao.findFirst(sql, Code.lc_ids, Code.bzlc_units, Code.ylc_capacity);
		if (p != null) {
			renderText(p.getStr(Product.column_ids));
		} else {
			renderText("");
		}
	}

	/**
	 * 获取消费金额
	 * 
	 */
	public void getCost() {
		// String delWeight=getPara("delWeight");
		String tem = getPara("tem");
		String productIds = getPara("productIds");
		// 获取当前登录机构id
		String orgids = getCUserOrganIds();
		RenderBean result = bentryRegisterService.getCost(tem, productIds, orgids);
		renderJson(result);
	}

	/**
	 * 协议预览（弹窗）
	 */
	public void showAgree() {
		String cusIds = getPara("customerIds");
		Customer cus = Customer.dao.findById(cusIds);
		setAttr("customer", cus);
		render("customerAgreement.html");
	}

	/**
	 * 基础资料（弹窗）
	 */
	public void showInfo() {
		String cusIds = getPara("customerIds");
		setAttr("customerIds", cusIds);
		List<BaseInfoSet> customerInfos = BaseInfoSet.dao.getChildByCustomer(cusIds);
		if (customerInfos.size() > 0) {
			setAttr("customerInfos", customerInfos);
		}
		setAttr("baseInfo", BaseInfoSet.dao.findById(BaseInfoSet.rootIds));
		render("customerDetail.html");
	}
	
	/**
	 * 修改资料（弹窗）
	 * @throws ParseException 
	 */
	public void toUpdateInfo() throws ParseException {
		String cusIds = getPara("customerIds");
		String cityStr = "";
		String areaStr = "";
		Customer customer = Customer.dao.findById(cusIds);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", CustomerDetail.column_customerIds); 
		String sql = getSqlByBeetl(CustomerDetail.sqlId_column, param);
		//IntoPersonnel personnel = IntoPersonnel.dao.findFirst(sql, intoPersonnel.getStr(IntoPersonnel.column_userIds));
		CustomerDetail customerDetail = CustomerDetail.dao.findFirst(sql,cusIds);
		if(customerDetail!=null){
			String cityIds = customerDetail.getStr(CustomerDetail.column_city);
			String areaIds = customerDetail.getStr(CustomerDetail.column_area);
			String sqllc = "SELECT sp.name FROM sys_code sp WHERE sp.ids =  ?";
			if(Db.findFirst(sqllc,cityIds)!=null){
				cityStr = Db.findFirst(sqllc,cityIds).getStr("name");
			}
			if(Db.findFirst(sqllc,areaIds)!=null){
				areaStr = Db.findFirst(sqllc,areaIds).getStr("name");
			}
		}
		
		
		String lcName = "";
		Map<String, Object> param2 = new HashMap<String, Object>();
		param2.put("column", CustomerDetail.column_customerIds); 
		String sql2 = getSqlByBeetl(CustomerAgreement.sqlId_column, param2);
		//IntoPersonnel personnel = IntoPersonnel.dao.findFirst(sql, intoPersonnel.getStr(IntoPersonnel.column_userIds));
		CustomerAgreement customerAgreement = CustomerAgreement.dao.findFirst(sql2,cusIds);
		if(customerAgreement!=null){
			String lcIds = customerAgreement.getStr(CustomerAgreement.column_codeIds);
			String sqllc = "SELECT sp.name FROM sb_product sp WHERE sp.ids = ?";
			if(Db.findFirst(sqllc,lcIds)!=null){
				lcName = Db.findFirst(sqllc,lcIds).getStr("name");
			}
		}
		/*Date firstDate = customerDetail.getDate(CustomerDetail.column_firstDate);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	    String dateStr = sdf.format(firstDate); 
	    String  firstDate2 = dateStr.substring(0,10);*/
	   
		setAttr("customer", customer);
		setAttr("customerDetail", customerDetail);
		setAttr("lcName", lcName);
		//setAttr("firstDate2", firstDate2);
		setAttr("cityStr", cityStr);
		setAttr("areaStr", areaStr);
		setAttr("organids", getCUserOrganIds());
		render("updateCustomerDetail.html");
	}
	
	/**
	 * 修改资料
	 */
	@Before(Tx.class)
	public void updateInfo() {
		Customer customer = getModel(Customer.class, "customer");
		CustomerDetail customerDetail = getModel(CustomerDetail.class, "customerDetail");
		JSONObject json = bentryRegisterService.updateInfo(customer,customerDetail,getCUserOrganIds(),getCUserIds());;
		renderJson(json);
		
//		JSONArray result = bentryRegisterService.updateInfo(customer,customerDetail,getCUserOrganIds(),getCUserIds());
//		renderJson(result);
	}

	/**
	 * 顾客产品（弹窗）
	 */
	public void customerProduct() {
		// String cusIds=getPara("customerIds");
		// Customer cus=Customer.dao.findById(cusIds);
		setAttr("customerIds", getPara("customerIds"));
		render("/customer/customerProdut.html");
	}

	public void getCusPro() {
		String cusIds = getPara("customerIds");
		String orgids = getPara("organIds", getCUserOrganIds());
		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put("orgids", orgids);
		queryParam.put("customerID", cusIds);
		LinkedList<Object> paramValue = new LinkedList<Object>();
		String sql = ToolSqlXml.getSqlMy(CustomerProduct.sqlId_selByCusAndOrg, queryParam,
				ConstantRender.sql_renderType_beetl, paramValue);
		List<Record> cpList = Db.find(sql, paramValue.toArray());
		renderJson(cpList);
	}

	/**
	 * 保存基础资料
	 */

	public void saveBaseInfo(){

		String organIds = getCUserOrganIds();
		String userIds = getCUserIds();
		CustomerHabit customerHabit = getModel(CustomerHabit.class,"customerHabit");
		
		RenderBean result = bentryRegisterService.saveBaseInfo(customerHabit,organIds,userIds);
		renderJson(result.getMap());

	}
	
	/**
	 * 保存日常
	 */

	public void saveDailyLife(){

		String organIds = getCUserOrganIds();
		String userIds = getCUserIds();
		CustomerHabit customerHabit = getModel(CustomerHabit.class,"customerHabit");
		
		RenderBean result = bentryRegisterService.saveDailyLife(customerHabit,organIds,userIds);
		renderJson(result.getMap());

	}

	/**
	 * 保存顾客登记信息
	 */
	@Before(Tx.class)
	public void saveCus() {
		Customer cus = getModel(Customer.class, "customer");
		CustomerDetail cusDet = getModel(CustomerDetail.class, "customerDetail");
		CustomerAgreement cusAgr = getModel(CustomerAgreement.class);
		// 获取当前登录机构id
		String orgids = getCUserOrganIds();
		RenderBean result = bentryRegisterService.saveCus(cus, cusDet, cusAgr, orgids);
		renderJson(result.getMap());
	}

	/**
	 * 图片上传
	 */
	public void imageUpload() {
		List<UploadFile> files = getFiles();
		// UploadFile uploadFile=getFile("zmfile");
		String cusIds = getPara("customerIds");
		JSONObject json = bentryRegisterService.imageUpload(files, cusIds);
		renderJson(json);
	}

	/**
	 * 获取code child
	 * 
	 */
	public void getChild() {
		System.out.println("............................");
		String codeIds = getPara("codeIds");
		String sql = getSqlMy(Code.sqlId_child);
		List<Code> cList = Code.dao.find(sql, codeIds);
		renderJson(cList);
	}

	/**
	 * 根据会员编号,手机号,姓名查出会员信息
	 * 
	 */
	public void getCusByHybh() {
		String hybh = getPara("hybh");
		String name = getPara("name");
		String phone = getPara("phone");
		// 获取当前登录机构id
		String orgid = getCUserOrganIds();
		Map<String, Object> mm = bentryRegisterService.getCusByHybh(hybh, name, phone, orgid);
		renderJson(mm);
	}
	
	
	/**
	 * 根据会员编号,手机号,姓名查出会员信息
	 * 
	 */
	public void getCusSizeByHybh() {
		String hybh = getPara("hybh");
		String date = getPara("date");
		String name = getPara("name");
		String phone = getPara("phone");
		// 获取当前登录机构id
		String orgid = getCUserOrganIds();
		Map<String, Object> mm = bentryRegisterService.getCusSizeByHybh(hybh, name, phone, orgid,date);
		renderJson(mm);
	}
	
	
	/**
	 * 获取会员名字/id
	 * 
	 */
	public void getCusInfo() {
		// 获取当前登录机构id
		String orgid = getCUserOrganIds();
		List<Customer> mm = bentryRegisterService.getCusInfo(orgid);
		renderJson(mm);
	}

	/**
	 * 上一个下一个
	 * 
	 */
	public void selOther() {
		String hybh = getPara("hybh");
		String obj = getPara("obj");
		// 获取当前机构id
		String organids = getCUserOrganIds();
		Customer cus = bentryRegisterService.selOther(hybh, obj, organids);
		if (cus != null) {
			CustomerAgreement cusagr = cus.getCustomerAgreement();
			Product p = Product.dao.findById(cusagr.getStr(CustomerAgreement.column_codeIds));
			if (p != null && p.getStr(Product.column_proUnits).equals(Code.dlc_units)) {
				setAttr("isdlc", "1");
			}
		}
		setAttr("customer", cus);
		setAttr("organids", organids);
		if (cus != null) {
			setAttr("chargePersion", cus.getCustomerDetail().getStr(CustomerDetail.column_chargePersion));
		}
		render("bentryRegister.html");
	}

	/**
	 * 获取顾客详情
	 */
	public void selCustomerInfo() {
		String customerIds = getPara("customerIds");
		Customer cus = Customer.dao.findById(customerIds);
		if (cus != null) {
			CustomerDetail cd = cus.getCustomerDetail();
			float sc_weight = cd.getFloat(CustomerDetail.column_firstWeight);
			float now_weight = cd.getFloat(CustomerDetail.column_nowWeight);
			setAttr("yijianWeight", sc_weight - now_weight);
			float del = cd.getFloat(CustomerDetail.column_delWeight);
			// 创建一个数值格式化对象
			NumberFormat numberFormat = NumberFormat.getInstance();
			// 设置精确到小数点后2位
			numberFormat.setMaximumFractionDigits(2);

			String wcbl = numberFormat.format((sc_weight - now_weight) / del * 100);

			CustomerService cs = Customer.dao.getCustomerServiceCount(customerIds, getCUserOrganIds());
			long count = cs.getLong("count");
			setAttr("count", count);
			setAttr("wcbl", wcbl + "%");
			setAttr("customer", cus);
		}
		render("/customer/customerInfoUl.html");
	}
	
	@Before(Tx.class)
	public void deleteCus(){
		String customerIds=getPara("customerIds");
		String msg= bentryRegisterService.deleteCus(customerIds,getCUserIds(),getCUserOrganIds());
		renderText(msg);
	}
	
	

}
